import React, { useState, useEffect } from 'react';
import {View, Text, FlatList, StyleSheet, TouchableOpacity} from 'react-native';
import { format, startOfMonth, endOfMonth, eachDayOfInterval, subDays } from 'date-fns';

const Calendar = ({ year, month, onChange, activeDate }) => {
    const [days, setDays] = useState([]);
    // const [activeDate, setActiveDate] = useState(null);

    useEffect(() => {
        const generateDates = () => {
            // 创建指定年份和月份的Date对象
            const start = startOfMonth(new Date(year, month - 1)); // 月份是从0开始计算的，所以减1
            const end = endOfMonth(new Date(year, month - 1));

            // 找到当前月第一天是星期几
            const firstDayOfWeek = start.getDay();

            // 如果月初不是星期天，补上前几天空白（前一个月的日期）
            const leadingEmptyDays = Array.from({ length: firstDayOfWeek }, (_, index) => {
                const date = subDays(start, firstDayOfWeek - index);
                return {
                    date: subDays(start, firstDayOfWeek - index), // 获取前几天的日期
                    isThan: Number(format(date, "yyyyMMdd")) >= Number(format(new Date(), "yyyyMMdd")),
                }
            });

            // 获取当前月份的所有日期
            const currentMonthDays = eachDayOfInterval({ start, end }).map(date => ({
                date,
                // isCurrentMonth: true,
                isThan: Number(format(date, "yyyyMMdd")) >= Number(format(new Date(), "yyyyMMdd")),
            }));
            console.log('currentMonthDays', currentMonthDays);

            // 合并空白日期和当前月日期
            const allDays = [...leadingEmptyDays, ...currentMonthDays];

            setDays(allDays);
        };

        generateDates();
    }, [year, month]);

    const changeActiveDate = function (item) {
        if (!item.isThan) return;
        onChange && onChange(item)
    };


    const renderDay = ({ item }) => {

        const tranFormDate = function (toDay, day) {
            return format(toDay, "yyyy-MM-dd") !== format(day, 'yyyy-MM-dd') ? format(day, 'dd') : "今天"
        };

        const activeStyles = function (date) {
            // console.log('item', item);
            return activeDate && format(date, "yyyy-MM-dd") === format(activeDate, 'yyyy-MM-dd')
        };

        const selectDateStyles = function (date) {
            // console.log('item', item);
            return activeDate && Number(format(date, "yyyyMMdd")) < Number(format(activeDate, 'yyyyMMdd')) && Number(format(date, "yyyyMMdd")) > Number(format(new Date(), 'yyyyMMdd'))
        };

        return (
            <View style={styles.dayContainer}>
                <TouchableOpacity onPress={() => changeActiveDate(item)}>
                    <Text style={
                        [
                            styles.dayText,
                            (!item.isThan) && styles.inactiveDay,
                            tranFormDate(new Date(), item.date) === '今天' && styles.todayColor,
                            activeStyles(item.date) && styles.activeStyle,
                            selectDateStyles(item.date) && styles.selectDateStyle,
                        ]
                    }>
                        {
                            tranFormDate(new Date(), item.date)
                        }
                    </Text>
                </TouchableOpacity>
            </View>
        );
    };

    return (
        <View style={styles.container}>
            <View style={styles.weekHeader}>
                {['日', '一', '二', '三', '四', '五', '六'].map((day, index) => (
                    <Text key={index} style={styles.weekHeaderText}>{day}</Text>
                ))}
            </View>

            <FlatList
                data={days}
                numColumns={7}
                keyExtractor={(item) => item.date.toString()}
                renderItem={renderDay}
            />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        // padding: 10,
        padding: 12,
    },
    weekHeader: {
        flexDirection: 'row',
        // justifyContent: 'space-around',
        justifyContent: "flex-start",
        marginBottom: 15,
    },
    weekHeaderText: {
        fontSize: 14,
        fontWeight: 'bold',
        width: 23,
        height: 20,
        // backgroundColor: 'red',
        marginRight: 30,
        textAlign: "center",
        lineHeight: 23,

    },
    dayContainer: {
        // flex: 1,
        // margin: 5,
        flexDirection: "row",
        justifyContent: "flex-start",
        // alignItems: 'center',


    },
    dayText: {
        fontSize: 12,
        textAlign: "center",
        lineHeight: 23,
        marginRight: 30,
        borderRadius: 10,
        width: 23,
        height: 36,
    },
    inactiveDay: {
        color: '#9C9EAC',
    },
    todayColor: {
        color: "#EC6138",
        fontSize: 12,
    },
    activeStyle: {
        width: 23,
        height: 23,
        overflow: "hidden",
        flexDirection: "row",
        backgroundColor: "#EC6138",
        borderRadius: 12,
        color: "#fff"
    },
    selectDateStyle: {
        width: 23,
        height: 23,
        overflow: "hidden",
        flexDirection: "row",
        backgroundColor: "#FFE9E3",
        borderRadius: 12,
        color: "#2A2B30",
        marginBottom: 20,
    },
});

export default Calendar;
